package com.edou.member.controller.admin;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.base.controller.BaseController;
import com.edou.base.token.TokenValidate;
import com.edou.member.entity.MemberCompany;
import com.edou.member.entity.MemberRole;
import com.edou.member.entity.MemberUser;
import com.edou.member.entity.MemberUserCompany;
import com.edou.member.entity.MemberUserRole;
import com.edou.member.form.MemberUserForm;
import com.edou.member.service.IMemberCompanyService;
import com.edou.member.service.IMemberRoleService;
import com.edou.member.service.IMemberUserCompanyService;
import com.edou.member.service.IMemberUserRoleService;
import com.edou.member.service.IMemberUserService;
import com.edou.system.entity.SysUploadSet;
import com.edou.system.service.ISysUploadSetService;



/**
 * 会员基本信息
 * @creator     
 * @create-time 2016/3/12 16:10:22
 * @email admin@edou.com
 * @company www.edou.com
 * @version 1.0
 */
@Controller("memberUserAdminController")
@Scope("prototype")
@RequestMapping("/admin/member")
public class MemberUserAdminController extends BaseController {

	@Resource(name = "memberUserServiceImpl")
	private IMemberUserService memberUserService;
	@Resource(name = "memberRoleServiceImpl")
	private IMemberRoleService memberRoleService;
	@Resource(name = "memberCompanyServiceImpl")
	private IMemberCompanyService memberCompanyService;
	@Resource(name = "memberUserRoleServiceImpl")
	private IMemberUserRoleService memberUserRoleService;
	@Resource(name = "memberUserCompanyServiceImpl")
	private IMemberUserCompanyService memberUserCompanyService;
	@Resource
	private ISysUploadSetService sysUploadSetService;
	
	/**
	 * 首页
	 * @return 
	 */
	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public ModelAndView index(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_user_index");
		Map<String, Object> data = view.getModel();
		// 会员角色
		List<MemberRole> memberRoleList = memberRoleService.listMemberRoleAll();
		data.put("memberRoleList", memberRoleList);
		return view;
	}
	
	
	
	/**
	 * 跳转到日对比
	 * @return 
	 */
	@RequestMapping(value = "/day.htm", method = RequestMethod.GET)
	public ModelAndView day(){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_operate_day");
		return  view;
	}
	
	/**
	 * 跳转到周对比
	 * @return 
	 */
	@RequestMapping(value = "/week.htm", method = RequestMethod.GET)
	public ModelAndView week(){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_operate_week");
		return  view;
	}
	
	/**
	 * 跳转到年对比
	 * @return 
	 */
	@RequestMapping(value = "/month.htm", method = RequestMethod.GET)
	public ModelAndView month(){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_operate_month");
		return  view;
	}
	
	/**
	 * 会员列表页 - 自定义列表属性
	 * @return 
	 */
	@RequestMapping(value = "/list_custom.htm", method = RequestMethod.GET)
	public String listCustom(){
		return "/admin/member/member_list_custom";
	}

	/**
	 * 分页查询
	 * @return 
	 */
	@RequestMapping(value = "/listMemberUserByPage.htm", method = RequestMethod.POST)
	public void listMemberUserByPage(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try{
			memberUserService.listMemberUserByPage(model.getPageResult(),model.getCondition());
			JSONObject root = toPageJson(model.getPageResult(), new String[]{
					"id","createDate","account","birthday","password","mobile","mobileTrue","email","emailTrue","state","approvalState","roleName","level","name","nickName","facePath","sex","descBrief","desc","qq","wechat","contactOther","address","remark",
					"company","memberUserCompany","birthday"});
			ajaxPageResult(root,response);
		}catch(Exception ex){
			String msg = "查询会员基本信息时发生异常："+ex.getMessage();
			logger.error(msg,ex);
		}
	}

	/**
	 * 保存会员基本信息
	 * @return 
	 */
	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public ModelAndView edit(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_user_add");
		Map<String,Object> data = view.getModel();
		if(StringUtils.isNotBlank(model.getItem().getId())){
			MemberUser item = memberUserService.getMemberUserById(model.getItem().getId());
			// 查询会员角色
			MemberUserRole memberUserRole = memberUserRoleService.getMemberUserRoleByUserId(model.getItem().getId());
			if(memberUserRole != null){
				item.setMemberRoleId(memberUserRole.getMemberRoleId());
			}
			// 查询会员医院
			MemberUserCompany memberUserCompanyHospital = memberUserCompanyService.getMemberUserCompanyByUserIdAndIsleaf(model.getItem().getId(), 1);
			if(memberUserCompanyHospital != null){
				item.setMemberCompanyHospitalId(memberUserCompanyHospital.getMemberCompanyId());
			}
			// 查询会员集团
			MemberUserCompany memberUserCompanyGroup = memberUserCompanyService.getMemberUserCompanyByUserIdAndIsleaf(model.getItem().getId(), 0);
			if(memberUserCompanyGroup != null){
				item.setMemberCompanyId(memberUserCompanyGroup.getMemberCompanyId());
			}
			data.put("item", item);
		}
		// 会员角色
		List<MemberRole> memberRoleList = memberRoleService.listMemberRoleAll();
		data.put("memberRoleList", memberRoleList);

		// 会员所在医院
		List<MemberCompany> memberCompanyHospitalList = memberCompanyService.listMemberCompanyByIsLeaf(1);
		data.put("memberCompanyHospitalList", memberCompanyHospitalList);
		// 会员所在集团
		List<MemberCompany> memberCompanyGroupList = memberCompanyService.listMemberCompanyByIsLeaf(0);
		data.put("memberCompanyGroupList", memberCompanyGroupList);
		
		return view;
	}

	/**
	 * 开通会员帐号
	 * @return 
	 */
	@RequestMapping(value = "/regist.htm", method = RequestMethod.GET)
	public ModelAndView regist(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_user_regist");
		Map<String,Object> data = view.getModel();
		
		return view;
	}
	
	/**
	 * 查看会员帐号
	 * @return 
	 */
	@RequestMapping(value = "/view.htm", method = RequestMethod.GET)
	public ModelAndView view(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_user_regist");
		Map<String,Object> data = view.getModel();
		
		String id = model.getItem().getId();
		if(StringUtils.isNotBlank(id)){
			MemberUser item = memberUserService.getMemberUserById(model.getItem().getId());
			data.put("item", item);
		}
		
		return view;
	}
	
	/**
	 * 客户或供应商开通会员-保存方法
	 * @return 
	 */
	@RequestMapping(value = "/do_open.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView doOpen(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpSession session){
		try {
			if(StringUtils.isBlank(model.getItem().getId())){
				memberUserService.doOpenMember(model.getItem(),model.getClientId());
			}else{
				memberUserService.update(model.getItem());
			}
			return ajaxJSON(Status.success,"保存成功");
		} catch (Exception e) {
			String msg = "保存会员基本信息时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	
	/**
	 * 保存会员基本信息
	 * @return 
	 */
	@RequestMapping(value = "/saveMemberUser.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView saveMemberUser(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpSession session){
		try {
			if(StringUtils.isBlank(model.getItem().getId())){
				memberUserService.add(model.getItem());
				
			}else{
				memberUserService.update(model.getItem());
			}
			return ajaxJSON(Status.success,"保存成功");
		} catch (Exception e) {
			String msg = "保存会员基本信息时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	
	/**
	 * 跳转到会员的修改密码页面
	 * @return 
	 */
	@RequestMapping(value = "/to_reset_pwd.htm", method = RequestMethod.GET)
	public ModelAndView toResetPwd(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_user_password_reset");
		Map<String,Object> data = view.getModel();
		
		String id = model.getId();
		MemberUser user = memberUserService.getMemberUserById(id);
		data.put("item", user);
		
		return view;
	}
	
	/**
	 * 重置密码
	 * @return
	 */
	@RequestMapping(value = "/resetPwd.htm", method = RequestMethod.POST)
	public ModelAndView resetPwd(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpSession session){
		try {
			MemberUser user = model.getItem();
			memberUserService.updatePwd(user);
			return ajaxJSON(Status.success,"重置成功");
		} catch (Exception e) {
			String msg = "重置密码时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error,"重置失败");
		}
	}
	
	/**
	 * 删除会员基本信息
	 * @return 
	 */
	@RequestMapping(value = "/del.htm", method = RequestMethod.POST)
	public ModelAndView del(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			memberUserService.delByIds(model.getSelIds().split(","));
			return ajaxJSON(Status.success,"删除成功");
		} catch (Exception e) {
			String msg = "删除会员基本信息时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "删除失败，请稍后重试");
		}
	}
	
	/**
	 * 修改会员状态
	 */
	@RequestMapping(value = "/updateState.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView updateState(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpSession session){
		try {
			memberUserService.updateStates(model.getSelIds().split(","),model.getItem().getState());
			return ajaxJSON(Status.success,"修改状态成功");
		} catch (Exception e) {
			String msg = "修改状态时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	/**
	 * 修改会员启用/禁用状态
	 * @return
	 */
	@RequestMapping(value = "/changeState.htm", method = RequestMethod.POST)
	public ModelAndView changeState(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			Integer state = model.getItem().getState();
			String memberId = model.getItem().getId();
			if(StringUtils.isNotBlank(memberId)){
				MemberUser member = memberUserService.getMemberUserById(memberId);
				member.setState(state);
				memberUserService.update(member);
			}
			return ajaxJSON(Status.success,"会员状态设置成功");
		} catch (Exception e) {
			String msg = "设置会员状态时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "会员状态设置失败，请稍后重试");
		}
	}
	
	/**
	 * 修改会员启用/禁用状态
	 * @return
	 */
	@RequestMapping(value = "/apprState.htm", method = RequestMethod.POST)
	public ModelAndView apprState(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			Integer apprState = model.getItem().getApprovalState();
			String memberId = model.getItem().getId();
			if(StringUtils.isNotBlank(memberId)){
				MemberUser member = memberUserService.getMemberUserById(memberId);
				member.setApprovalState(apprState);
				memberUserService.update(member);
			}
			return ajaxJSON(Status.success,"会员状态设置成功");
		} catch (Exception e) {
			String msg = "设置会员状态时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "会员状态设置失败，请稍后重试");
		}
	}

	/**
	 * 查看会员基本信息
	 * @return 
	 */
	@RequestMapping(value = "/look.htm", method = RequestMethod.GET)
	public ModelAndView look(@ModelAttribute MemberUserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_user_index_look");
		Map<String,Object> data = view.getModel();
		if(StringUtils.isNotBlank(model.getItem().getId())){
			MemberUser memberUserById = memberUserService.getMemberUserById(model.getItem().getId());
			List<MemberRole> listMemberRole = memberRoleService.listMemberRoleByUserId(memberUserById.getId());
			if(memberUserById  != null){
				if (memberUserById.getCompany()!=null) {
					MemberCompany memberCompanyById = memberCompanyService.getMemberCompanyById(memberUserById.getCompany().getId());
					data.put("memberCompany", memberCompanyById);
				}
			}
			data.put("memberRole", listMemberRole);
			data.put("member", memberUserById);
		}
		return view;
	}
	
	/***
	 * 日对比
	 */
	@RequestMapping(value="listDayOperateForCreateDate.htm",method = RequestMethod.POST)
	public void listDayOperateForCreateDate(@ModelAttribute MemberUserForm model, HttpServletRequest request,HttpServletResponse response){
		
		try {
			List<MemberUser> DayOperateForCreateDateList = memberUserService.listDayOperateForCreateDate(model.getCondition());
			JSONObject root = toJsonResultList(DayOperateForCreateDateList, new String[] { "id", "num", "day"});
			ajaxPageResult(root, response);
		} catch (Exception ex) {
			String msg = "查询日对比时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
		}
	}
	
	/***
	 * 周对比
	 */
	@RequestMapping(value="listWeekOperateForCreateDate.htm",method = RequestMethod.POST)
	public void listWeekOperateForCreateDate(@ModelAttribute MemberUserForm model, HttpServletRequest request,HttpServletResponse response){
		try {
			List<MemberUser> weekOperateForCreateDateList = memberUserService.listWeekOperateForCreateDate(model.getCondition());
			JSONObject root = toJsonResultList(weekOperateForCreateDateList, new String[] { "id", "num", "week"});
			ajaxPageResult(root, response);
		} catch (Exception ex) {
			String msg = "查询周对比时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
		}
	}
	
	/***
	 * 月对比
	 */
	@RequestMapping(value="listMonthOperateForCreateDate.htm",method = RequestMethod.POST)
	public void listMonthOperateForCreateDate(@ModelAttribute MemberUserForm model, HttpServletRequest request,HttpServletResponse response){
		try {
			List<MemberUser> monthOperateForCreateDateList = memberUserService.listMonthOperateForCreateDate(model.getCondition());
			JSONObject root = toJsonResultList(monthOperateForCreateDateList, new String[] { "id", "num", "months"});
			ajaxPageResult(root, response);
		} catch (Exception ex) {
			String msg = "查询月对比时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
		}
	}
	
	
	/**
	 * 跳转到实名认证页面审核
	 * @param model
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/toRealNameCertInfo.htm", method = RequestMethod.GET)
	public ModelAndView toRealNameCertInfo(@ModelAttribute MemberUserForm model, HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_cert_index");
		return view;
	}
	
	/**
	 * 实名认证信息- 分页查询
	 * @param model
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/listRealNameCertInfoByPage.htm", method = RequestMethod.POST)
	public void realNameCertInfoByPage(@ModelAttribute MemberUserForm model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			memberUserService.listMemberUserByPage(model.getPageResult(), model.getCondition());
			JSONObject root = toPageJson(model.getPageResult(),
					new String[] { "id", "nickName", "name", "certIdcard", "certState","certIdcardPath"});
			ajaxPageResult(root, response);
		} catch (Exception ex) {
			String msg = "查询会员基本信息时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
		}
	}
	
	/**
	 * 实名认证信息- 查看证件照
	 * @param model
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/lookCertIdcardPhoto.htm", method = RequestMethod.GET)
	public ModelAndView lookCertIdcardPhoto(@ModelAttribute MemberUserForm model, HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/member/member_cert_paperwork_photo");
		Map<String,Object> data= view.getModel();
		data.put("memberUser", memberUserService.getMemberUserById(model.getItem().getId()));
		return view;
	}
	
	/**
	 * 读取本地图片输出至客户端
	 * @param model
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/readLocalImgWriteToClient.htm", method = RequestMethod.GET)
	public void readLocalImgWriteToClient(@ModelAttribute MemberUserForm model, HttpServletRequest request,
			HttpServletResponse response) {
		MemberUser memberUserById = memberUserService.getMemberUserById(model.getItem().getId());
		SysUploadSet uploadSet = sysUploadSetService.getSysUploadSet();
		String uploadPath = uploadSet.getPrivateRoot();
		String readImgPath = uploadPath + memberUserById.getCertIdcardPath();
		//测试路径
		//String readImgPath = "d:\\UPLOAD\\20161019\\11.png"; 
        FileInputStream is;  
        try {
			is = new FileInputStream(readImgPath);  
			int i = is.available(); // 得到文件大小  
			byte data[] = new byte[i];  
			is.read(data); // 读数据  
			is.close();  
			response.setContentType("image/*"); // 设置返回的文件类型  
			OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象  
			toClient.write(data); // 输出数据  
			toClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	
	/**
	 * 实名认证信息- 批量审核
	 * @param model
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/auditingCertByIds.htm", method = RequestMethod.POST)
	public ModelAndView auditingCertByIds(@ModelAttribute MemberUserForm model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			memberUserService.modifyCertState(model.getSelIds().split(","),model.getItem().getCertState());
			return ajaxJSON(Status.success,"审核成功");
		} catch (Exception e) {
			String msg = "审核时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "审核失败，请稍后重试");
		}
	}
}